package com.zline.foodraise.ui.activity;

import android.content.ContentValues;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.GravityEnum;
import com.afollestad.materialdialogs.MaterialDialog;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.photoselector.util.CommonUtils;
import com.zline.foodraise.R;
import com.zline.foodraise.constant.Constant;
import com.zline.foodraise.entity.AppPref_;
import com.zline.foodraise.entity.TagBean;
import com.zline.foodraise.entity.UserBean;
import com.zline.foodraise.http.HttpDataParsing;
import com.zline.foodraise.http.HttpErro;
import com.zline.foodraise.http.HttpOperator;
import com.zline.foodraise.http.HttpUtil;
import com.zline.foodraise.util.ImageUtil;
import com.zline.foodraise.util.LUtil;
import com.zline.foodraise.util.NetworkUtil;
import com.zline.foodraise.util.TUtil;
import com.zline.foodraise.view.CircleImageView;
import com.zline.foodraise.view.SexSetDialog_;
import com.zline.foodraise.view.dialog.LoadingProgressDialog;

import org.androidannotations.annotations.AfterInject;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.OnActivityResult;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.StringRes;
import org.androidannotations.annotations.sharedpreferences.Pref;
import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

/**
 * Created by heshantao on 15/6/30.
 * 个人信息设置
 */
@EActivity(R.layout.activity_personal_info_setting)
public class PersonalInformationSettingActivity extends ZlineActivity {
    private static final String LOG_TAG = PersonalInformationSettingActivity.class.getSimpleName();
    @ViewById(R.id.logout_btn)
    Button logout_btn;
    @ViewById(R.id.app_common_header_title_tv)
    TextView title_tv;
    //标题
    @StringRes(R.string.personal_info_title)
    String title;
    @StringRes(R.string.take_new_picture)
    String take_new_pic;
    @StringRes(R.string.chose_from_gallery)
    String chose_from_gallery;
    @Bean
    ImageUtil imageUtil;
    //头像
    @ViewById(R.id.personal_info_set_icon_circleIv)
    CircleImageView circleImageView;
    //昵称
    @ViewById(R.id.personal_info_set_nickname_value_tv)
    TextView nickename_tv;
    String nickname;
    //性别
    @ViewById(R.id.personal_info_set_sex_value_tv)
    TextView sex_tv;
    //性别
    String sex;
    int sexFlag;
    //签名
    @ViewById(R.id.personal_info_set_sigature_value_tv)
    TextView signature_tv;
    String signature;
    //标签
    List<TagBean> tags = new ArrayList<TagBean>();
    //用户说明
    String userDes;
    //手机号
    @ViewById(R.id.personal_info_set_phone_value_tv)
    TextView mobile_tv;
    String mobile;
    @StringRes(R.string.boy)
    String boy;
    @StringRes(R.string.girl)
    String girl;

    Intent intent;
    Uri imageUri;
    Uri crop_imageUri;
    //剪切后图片存储路径
    String crop_image_url;
    Bitmap bitmap;
    @Pref
    AppPref_ appPref;
    long userId;
    @Bean
    HttpOperator httpOperator;
    @Bean
    HttpUtil httpUtil;
    int resultCode = 0;
    @Bean
    HttpErro httpErro;
    @Bean
    HttpDataParsing httpDataParsing;
    //标志1.头像 2.背景图
    int flag = -1;
    MaterialDialog logoutDialog;
    LoadingProgressDialog uploadDialog;
    @Bean
    NetworkUtil networkUtil;

    @AfterInject
    void doSomeAfterInject() {
        userId = appPref.userId().get();
    }

    @AfterViews
    void doSomeAfterViews() {
        crop_image_url = imageUtil.getDiskFileDir(Constant.TEMP) + "/avatar_" + String.valueOf(System.currentTimeMillis()) + ".png";
        crop_imageUri = Uri.fromFile(new File(crop_image_url));
        initView();
    }

    void initView() {
        title_tv.setText(title);
        if (networkUtil.isNetworkAvailable()) {
            showLoadingDialog();
            requestUserInfo();
        } else {
            TUtil.showShort(this, R.string.fail_load_data);
        }

    }

    //请求用户基本信息
    void requestUserInfo() {
        httpOperator.requestUserInfo(httpUtil, userId, requestUserInfoHandler);
    }

    //获取用户基本信息回调
    AsyncHttpResponseHandler requestUserInfoHandler = new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            LUtil.i(LOG_TAG, "____successs_____requestUserInfoHandler_____" + statusCode + response.toString());
            if (statusCode == 200) {
                try {
                    resultCode = response.getInt(Constant.RESULT_CODE);
                    if (resultCode == 200) {//调用成功
                        UserBean userBean = httpDataParsing.getUserBean(response);
                        setUserInfo(userBean);
                    } else {
                        httpErro.showCommonErroResult(resultCode);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } finally {
                    dissLoadingDialog();
                }
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
            dissLoadingDialog();
        }
    };


    //设置用户基本信息
    void setUserInfo(UserBean userBean) {
        if (userBean != null) {
            ImageLoader imageLoader = ImageLoader.getInstance();
            DisplayImageOptions person_icon_options = imageUtil.
                    getDisplayImageOptions(R.mipmap.default_person_icon,
                            R.mipmap.default_person_icon, R.mipmap.default_person_icon);

            String picUrl = userBean.getAvatarPicUrl();
            imageLoader.displayImage(picUrl, circleImageView, person_icon_options);
            nickname = userBean.getNickName();
            nickename_tv.setText(nickname);
            sex = userBean.getSex() == 1 ? boy : girl;
            sex_tv.setText(sex);
            signature = userBean.getSignature();
            signature_tv.setText(signature);
            mobile = userBean.getMobile();
            //使手机格式显示为：150****1029
            if (mobile.length() > 7) {
                String subMobile = mobile.substring(3, 7);
                mobile = mobile.replace(subMobile, "****");
            }
            mobile_tv.setText(mobile);
            userDes = userBean.getUserDesc();
            tags = userBean.getTagBeanList();
        }
    }


    //更改照片/背景
    void openChosePicDialog() {
        new MaterialDialog.Builder(PersonalInformationSettingActivity.this)
                .itemsGravity(GravityEnum.CENTER)
                .itemColorRes(R.color.red)
                .items(new String[]{take_new_pic, chose_from_gallery})
                .itemsCallback(new MaterialDialog.ListCallback() {
                    @Override
                    public void onSelection(MaterialDialog materialDialog, View view, int position, CharSequence charSequence) {
                        switch (position) {
                            case 0:
                                takePicFromCamera();
                                break;
                            case 1:
                                takeImageFromGallery();
                                break;
                            default:
                                break;
                        }
                    }
                })
                .show();

    }

    //性别设置
    void openChoseSexDialog() {
        View customView = SexSetDialog_.build(this);
        final MaterialDialog dialog = new MaterialDialog.Builder(PersonalInformationSettingActivity.this)
                .customView(customView, false)
                .show();
        RelativeLayout girl_rl = (RelativeLayout) customView.findViewById(R.id.sex_set_girl_rl);
        RelativeLayout boy_rl = (RelativeLayout) customView.findViewById(R.id.sex_set_boy_rl);
        girl_rl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sexFlag = 0;
                requestSetSex(sexFlag);
                dialog.dismiss();

            }
        });

        boy_rl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sexFlag = 1;
                requestSetSex(sexFlag);
                dialog.dismiss();
            }
        });
    }

    //请求修改性别
    void requestSetSex(int sex) {
        if (networkUtil.isNetworkAvailable()) {
            httpOperator.requstModifyPersonalSex(httpUtil, sex, requestSexHandler);
        } else {
            TUtil.showShort(this, R.string.no_network);
        }
    }

    //修改个人性别回调
    AsyncHttpResponseHandler requestSexHandler = new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            LUtil.i(LOG_TAG, "____successs_____requestSexHandler_____" + statusCode + response.toString());
            if (statusCode == 200) {
                try {
                    resultCode = response.getInt(Constant.RESULT_CODE);
                    if (resultCode == 200) {//调用成功
                        setSexText();
                    } else {
                        httpErro.showCommonErroResult(resultCode);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
        }
    };

    @UiThread
    void setSexText() {
        sex = sexFlag == 1 ? boy : girl;
        sex_tv.setText(sex);
    }

    //从相机中选择
    void takePicFromCamera() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            /***
             * 需要说明一下，以下操作使用照相机拍照，拍照后的图片会存放在相册中的
             * 这里使用的这种方式有一个好处就是获取的图片是拍照后的原图
             * 如果不实用ContentValues存放照片路径的话，拍照后获取的图片为缩略图不清晰
             */
            ContentValues values = new ContentValues();
            imageUri = this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            startActivityForResult(intent, Constant.REQUEST_CODE_CAMERA);
        } else {
            TUtil.showShort(this, R.string.SD_card_not_exit);
        }
    }


    //去gallery中获取图片
    void takeImageFromGallery() {
        intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        startActivityForResult(intent, Constant.REQUEST_CODE_FILE);
    }


    /**
     * 裁剪头像方法实现
     */
    void startPersonPicZoom(int outputX, int outputY) {
        intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(imageUri, "image/*");
        // 设置裁剪  
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例  
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高  
        intent.putExtra("outputX", outputX);
        intent.putExtra("outputY", outputY);
        intent.putExtra("scale", true);
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG);//图片的输出格式
        intent.putExtra(MediaStore.EXTRA_OUTPUT, crop_imageUri);
        intent.putExtra("noFaceDetection", true);
        startActivityForResult(intent, Constant.REQUEST_CODE_CROP);
    }

    /**
     * 裁剪背景 方法实现
     */
    void startPersonBgZoom(int outputX, int outputY) {
        intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(imageUri, "image/*");
        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 3);
        intent.putExtra("aspectY", 2);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", outputX);
        intent.putExtra("outputY", outputY);
        intent.putExtra("scale", true);
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG);//图片的输出格式
        intent.putExtra(MediaStore.EXTRA_OUTPUT, crop_imageUri);
        intent.putExtra("noFaceDetection", true);
        startActivityForResult(intent, Constant.REQUEST_CODE_CROP);
    }

    //剪切以后处理返回结果
    void setCropImage(Uri uri) {
        String imagePath = uri.getPath().toString();
        openUploadDialog();
        imageUtil.decodeAndCompressImageByQuality(imagePath);
        uploadPic(imagePath);
        bitmap = BitmapFactory.decodeFile(imagePath);
    }


    //图片上传对话框
    void openUploadDialog() {
        uploadDialog = LoadingProgressDialog.init(this);
        uploadDialog.show();
    }

    void dismissUploadDialog() {
        if (uploadDialog != null && uploadDialog.isShowing()) {
            uploadDialog.dismiss();
        }
    }

    //退出登录框
    void openLogoutDialog() {
        logoutDialog = new MaterialDialog.Builder(this)
                .title(R.string.warm_prompt)
                .titleGravity(GravityEnum.CENTER)
                .content(R.string.logout_dialog_content)
                .positiveText(R.string.ok)
                .negativeText(R.string.cancel)
                .callback(new MaterialDialog.ButtonCallback() {
                    @Override
                    public void onNegative(MaterialDialog dialog) {
                        super.onNegative(dialog);
                        logoutDialog.dismiss();
                    }

                    @Override
                    public void onPositive(MaterialDialog dialog) {
                        super.onPositive(dialog);
                        clearData();
                        logoutDialog.dismiss();
                    }
                })
                .show();
    }

    //清除用户的登录信息的信息
    void clearData() {
        appPref.edit().userId().put(-1).apply();
        appPref.edit().token().put("").apply();
        JPushInterface.setAliasAndTags(this, "", null, mAliasCallback);
        MainActivity_.intent(this).isLogOut(true).start();
        finish();

    }

    //推送设置别名回调
    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {
        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs ;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    LUtil.i(LOG_TAG, logs);
                    break;
                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    LUtil.i(LOG_TAG, logs);
                    cancelSetAliase();
                    break;
                default:
                    logs = "Failed with errorCode = " + code;
                    LUtil.i(LOG_TAG, logs);
            }
        }
    };

    //取消以前的别名设置
    @Background(delay = 60000)
    void cancelSetAliase(){
        JPushInterface.setAliasAndTags(this, "", null, mAliasCallback);
    }


    @OnActivityResult(Constant.REQUEST_CODE_CAMERA)
    void onResultCamera(int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }
        imageUtil.roateBitmap(imageUri);
        if (flag == 1) {
            startPersonPicZoom(100, 100);
        } else if (flag == 2) {
            startPersonBgZoom(720, 420);
        }
    }

    @OnActivityResult(Constant.REQUEST_CODE_FILE)
    void onResultFile(int resultCode, Intent data) {
        if (resultCode != RESULT_OK || data == null) {
            return;
        }
        imageUri = data.getData();
        if (flag == 1) {
            startPersonPicZoom(100, 100);
        } else if (flag == 2) {
            startPersonBgZoom(720, 410);
        }
    }


    @OnActivityResult(Constant.REQUEST_CODE_CROP)
    void onResultPicZoom(int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }
        setCropImage(crop_imageUri);
    }


    //请求修改背景。头像
    void uploadPic(String imagePath) {
        if (networkUtil.isNetworkAvailable()) {
            httpOperator.requestUpdateUserPic(httpUtil, imagePath, flag, requestUploadPicHandler);
        } else {
            TUtil.showShort(this, R.string.no_network);
        }
    }

    //请求修改背景。头像回调
    AsyncHttpResponseHandler requestUploadPicHandler = new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            LUtil.i(LOG_TAG, "____successs_____requestUploadPicHandler_____" + statusCode + response.toString());
            if (statusCode == 200) {
                try {
                    resultCode = response.getInt(Constant.RESULT_CODE);
                    if (resultCode == 200) {//调用成功
                        if (bitmap != null) {
                            if (flag == 1) {
                                //个人头像图片本地保存
                                if (response.opt(Constant.URL) != null &&
                                        !response.isNull(Constant.URL) &&
                                        response.get(Constant.URL) != JSONObject.NULL) {
                                    String userIcon = response.getString(Constant.URL);
                                    appPref.edit().userIcon().put(userIcon).apply();
                                }
                                //设置头像
                                circleImageView.setImageBitmap(bitmap);
                            }
                        }
                    } else {
                        httpErro.showCommonErroResult(resultCode);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } finally {
                    dismissUploadDialog();
                }
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
            dismissUploadDialog();
        }
    };


    @OnActivityResult(Constant.PERSONAL_INFO_REQUEST_CODE)
    void onActivityResult(int resultCode, Intent data, @OnActivityResult.Extra String value) {
        switch (resultCode) {
            case Constant.SIGNATURE_RESULT_CODE:
                signature = value;
                signature_tv.setText(value);
                break;
            case Constant.NICK_NAME_RESULT_CODE:
                nickname = value;
                nickename_tv.setText(value);
                break;
            case Constant.PERSONAL_DECALER_RESULT_CODE:
                userDes = value;
                break;
            default:
                break;
        }
    }


    @Click({R.id.personal_info_set_nickname_rl, R.id.personal_info_set_sigature_rl,
            R.id.personal_info_set_change_bg_rl, R.id.personal_info_set_icon_rl,
            R.id.app_common_header_left_icon_iv, R.id.personal_info_set_sex_rl,
            R.id.personal_info_set_tag_rl, R.id.personal_info_set_addr_rl,
            R.id.logout_btn, R.id.personal_info_set_declare_rl
    })
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.personal_info_set_nickname_rl:
                ChangeNickNameActivity_.intent(this).nick_name(nickname).startForResult(Constant.PERSONAL_INFO_REQUEST_CODE);
                break;
            case R.id.personal_info_set_sigature_rl:
                SignatureSetActivity_.intent(this).signature(signature).startForResult(Constant.PERSONAL_INFO_REQUEST_CODE);
                break;
            case R.id.personal_info_set_change_bg_rl:
                flag = 2;
                openChosePicDialog();
                break;
            case R.id.personal_info_set_icon_rl:
                flag = 1;
                openChosePicDialog();
                break;
            case R.id.app_common_header_left_icon_iv:
                goback();
                break;
            case R.id.personal_info_set_sex_rl:
                openChoseSexDialog();
                break;
            case R.id.personal_info_set_tag_rl:
                PersonalTagSetActivity_.intent(PersonalInformationSettingActivity.this).resourceId(userId).resourceType(1).start();
                break;
            case R.id.personal_info_set_addr_rl:
                AddrListActivity_.intent(PersonalInformationSettingActivity.this).start();
                break;
            case R.id.logout_btn:
                openLogoutDialog();
                break;
            case R.id.personal_info_set_declare_rl:
                PersonalDeclareActivity_.intent(this).personalDeclare(userDes).startForResult(Constant.PERSONAL_INFO_REQUEST_CODE);
                break;
            default:
                break;
        }

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (bitmap != null && !bitmap.isRecycled()) {
            // 回收并且置为null
            bitmap.recycle();
            bitmap = null;
        }
    }
}
